﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Bilibili.Common.Database.Table;
using Bilibili.Common.Database;
using Bilibili.Model.Danmaku;
using PCLUntils.Json;
using PCLUntils.Objects;

namespace Bilibili.WebClient.Api
{
    public sealed class DanmakuFilterClient: ClientBase
    {
        public async Task<bool> Add(int type, string data, string csrf)
        {
            try
            {
                var url = string.Format("type={0}&filter={1}&jsonp=jsonp&csrf={2}", type, Uri.EscapeDataString(data), csrf);
                string results = await ApiClient.PostResults("http://api.bilibili.com/x/dm/filter/user/add", url, Current.HOST);
                var obj = results.ToJObject();
                if (obj.IsNotEmpty())
                {
                    if (obj["code"].ToInt32() == 0)
                    {
                        using DB db = new DB();
                        var oid = obj["data"]["id"].ToString();
                        SettingHelper.AddDanmakuFilter(db, type, oid, data);
                        return true;
                    }
                }
            }
            catch { }
            return false;
        }
        public async Task<List<DanmakuFilterTab>> Get(int type)
        {
            string results = await ApiClient.GetResults("http://api.bilibili.com/x/dm/filter/user?jsonp=jsonp");
            var fm = results.ParseObject<DanmakuFilter>();
            if (fm.Code == 0)
            {
                using DB db = new DB();
                if (fm.Data.Rule != null && fm.Data.Rule.Count > 0)
                {
                    var items = fm.Data.Rule.Where(x => x.Type == type);
                    foreach (var item in items)
                    {
                        var oid = item.Id.ToString();
                        SettingHelper.AddDanmakuFilter(db, type, oid, item.Filter);
                    }
                }
            }
            return GetFromDB(type);
        }
        public async Task Delete(IEnumerable<string> ids, int type, string csrf)
        {
            using DB db = new DB();
            foreach (var id in ids)
            {
                var url = string.Format("ids={0}&jsonp=jsonp&csrf={1}", id, csrf);
                string results = await ApiClient.PostResults("https://api.bilibili.com/x/dm/filter/user/del", url, Current.HOST);
                var obj = results.ToJObject();
                if (obj.IsNotEmpty())
                {
                    if (obj["code"].ToInt32() == 0)
                        SettingHelper.RemoveDanmakuFilter(id, type);
                    Thread.Sleep(10);
                }
            }
        }
        public List<DanmakuFilterTab> GetFromDB(int? type = 0)
        {
            return SettingHelper.GetDanmakuFilter(type);
        }
    }
}